import React, { Component } from 'react'
import { Layout, Drawer, Menu, Dropdown, Icon, ConfigProvider } from 'antd'
import 'antd/dist/antd.css'
import { BrowserRouter as Router, Route, HashRouter } from 'react-router-dom'
import zhCN from 'antd/lib/locale-provider/zh_CN'
import axios from '../../rudexRou/urlHttp.js'
import {
  uncompileStr,
  VerifySessionTime,
  getCookie,
  compileStr,
  delCookie,
  getResponseUrl,
  getLinkToUrl,
  devProTest,
  findConfig,
  getHeaderParams,
} from '../../rudexRou/OperatesCookie.js'
import routers from '../../rudexRou/routers.js'
import { dataAxios } from '../../rudexRou/request.js'
import Leftmenu from './Leftmenu.jsx'
import './SecondPages.css'
import HeaderMenu from './HeaderMenu.jsx'
import { getAllDept, getRoleInfo } from '../../api'
import { getConfigurationData } from '../../api2'
const { Header, Footer, Content, Sider } = Layout
const { SubMenu } = Menu
class SecondPages extends Component {
  constructor(props) {
    super(props)
    this.state = {
      drawerVisible: false,
      current: '1',
      JudgeWhetherOrNotShowTable: [],
      MenuData: [],
      userInfo: [],
      roleList: [],
      resultList: [],
      core: [],
      IsBg: false,
      IsCu: false,
      mainWidth: 'calc(100% - 208px)', //如果注释左侧菜单需要修改mainWidth为100%，默认值为calc(100% - 208px)
      setLeftMenu: true,
      isShow: true,
      IsMenus: false, //localStorage中是否有菜单,
      loading: false,
    }
    this.userInfo = {}
  }

  getDictionary() {
    const getDictionaryConfig = (list) => {
      return list.map((item) => {
        let children = []
        if (item.children && item.children.length > 0) {
          children = getDictionaryConfig(item.children)
        }
        return {
          code: item.code,
          label: item.name,
          values: children,
        }
      })
    }
    let dictionaryList = []
    let data = {
      currentPage: 1,
      pageSize: 999,
    }
    //发起请求
    getConfigurationData(data).then((res) => {
      if (res.data.code === 200) {
        dictionaryList = getDictionaryConfig(res.data.data.list)
        localStorage.setItem('dictionary', JSON.stringify(dictionaryList))
      } else {
      }
    })
  }
  getDeptData(data) {
    const treeList = []
    let map = {}
    for (var item of data) {
      if (!map['bg' + item.bgNo]) {
        treeList.push({
          value: item.bgNo,
          label: item.bgName,
          parentCode: -1,
          type: 'bg',
        })
      }
      if (item.bdNo && !map['bd' + item.bdNo]) {
        treeList.push({
          value: item.bdNo,
          label: item.bdName,
          parentCode: item.bgNo,
          type: 'bd',
        })
      }
      if (item.buNo && !map['bu' + item.buNo]) {
        treeList.push({
          value: item.buNo,
          label: item.buName,
          parentCode: item.bdNo,
          type: 'bu',
        })
      }
      if (item.cuNo && !map['cu' + item.cuNo]) {
        treeList.push({
          value: item.cuNo,
          label: item.cuName,
          parentCode: item.buNo,
          type: 'cu',
        })
      }
      map['bg' + item.bgNo] = item.bgName
      map['bd' + item.bdNo] = item.bdName
      map['bu' + item.buNo] = item.buName
      map['cu' + item.cuNo] = item.cuName
    }
    return treeList
  }
  getDeptTree(data) {
    let result = []
    if (!Array.isArray(data)) {
      return result
    }
    data.forEach((item) => {
      delete item.children
    })
    let map = {}
    data.forEach((item) => {
      map[item.value] = item
    })
    data.forEach((item) => {
      let parent = map[item.parentCode]
      if (parent) {
        ;(parent.children || (parent.children = [])).push(item)
      } else {
        result.push(item)
      }
    })
    return result
  }
  filterDept(role, data) {
    const type = role.type.replace('no', '')
    if (data && data.children) {
      data.children.forEach((item) => {
        if (item.type === type && item.value === role.value) {
          const temp = this.state.resultList
          temp.push(item)
          this.setState({ resultList: temp })
        } else {
          this.filterDept(role, item)
        }
      })
    }
  }
  getDeptList() {
    let deptList = []
    let params = {bgCode:"10019045"}
    getAllDept(params).then((response) => {
      if (response.data && response.data.data) {
        deptList = this.getDeptTree(this.getDeptData(response.data.data))
      }
      localStorage.setItem('deptList', JSON.stringify(deptList[0].children ))
      // this.state.roleList.forEach((role) => {
      //   this.filterDept(role, deptList[0])
      // })
      this.setState({ loading: true })
      // localStorage.setItem('deptList', JSON.stringify(this.state.resultList))
    })
  }
  getRoleInfo() {
    // let empList = []
    getRoleInfo().then((response) => {
      if (response.data && response.data.data) {
        let roleCode=[]
        response.data.data.forEach((item) => {
          if (item.routeId === 'mag-tmfs-exam-platform-manage') {
            roleCode.push(item.roleCode)
            const typeList = item.departmentTypes
              ? item.departmentTypes.split(',')
              : []
            const regionList = item.regionnoValues
              ? item.regionnoValues.split(',')
              : []
            sessionStorage.setItem('regionList', JSON.stringify(regionList))
            const valueList = item.departmentValues
              ? item.departmentValues.split(',')
              : []
            const roleList = []
            if (
              typeList.length > 0 &&
              valueList.length > 0 &&
              typeList.length === valueList.length
            ) {
              for (let i = 0; i < typeList.length; i++) {
                roleList.push({
                  type: typeList[i],
                  value: valueList[i],
                })
              }
              this.setState({ roleList })
              // this.getDeptList()
            }
          }
        })
        sessionStorage.setItem("roleCode",roleCode)
        this.getDeptList()
      }
      // localStorage.setItem('empList', JSON.stringify(empList))
    })
  }
  getPreConfig() {
    this.getDictionary()
    this.getRoleInfo()
  }
  componentWillMount() {
    this.getPreConfig()
  }
  //通过接口获取菜单
  getMenus() {
    let url = '/auth/queryMenusByToken'
    if (devProTest() === 'develop') {
      url = '/tmfs/icanApi/auth/queryMenusByToken'
    }
    dataAxios({
      url: url,
      type: 'get',
    })
      .then((response) => {
        if (response.status === 200) {
          if (response.data.code === 200 && response.data.message == 'OK') {
            localStorage.setItem('config', JSON.stringify(response.data.data))
            this.setState({ IsMenus: true })
          }
        }
      })
      .catch((error) => {
        console.log(error)
      })
  }
  componentDidMount() {
    //本地有参数
    let data = localStorage.getItem('config')
      ? JSON.parse(localStorage.getItem('config'))
      : null
    // let pathObj = getHeaderParams()
    if (devProTest() === 'develop') {
      //本地setItem(因为从5002调到5004 token不见了)
      // window.localStorage.setItem('refreshToken', pathObj.refreshToken)
      // window.localStorage.setItem('authToken', pathObj.authToken)
      // let userAccount = pathObj.userAccount
      // window.localStorage.setItem('empNo', '198681')
      // window.localStorage.setItem('userAccount', pathObj.userAccount)
      //   window.localStorage.setItem('userAccount', pathObj.userAccount)
      // this.getUserInfoOfIts(pathObj.userAccount);
    } else {
      //线上无参数
      let userInfo = window.localStorage.getItem('userInfo')
      this.userInfo = JSON.parse(userInfo)
      this.setState({
        JudgeWhetherOrNotShowTable: [{ ...this.userInfo }],
      })
    }
    if (data == null) {
      this.getMenus()
    } else {
      this.setState({ IsMenus: true })
    }
  }
  componentWillReceiveProps(nextProps) {}
  setLeftMenu = () => {
    this.setState({ setLeftMenu: !this.state.setLeftMenu }, () => {
      if (this.state.setLeftMenu === false) {
        this.setState({ mainWidth: '100%' }, () => {
          //各自主页面如果有 window.onresize，会执行触发，如果没有 则无需关注
          var event2 = document.createEvent('HTMLEvents')
          event2.initEvent('resize', false, true)
          window.dispatchEvent(event2)
        })
      } else {
        this.setState({ mainWidth: 'calc(100% - 208px)' }, () => {
          //各自主页面如果有 window.onresize，会执行触发，如果没有 则无需关注
          var event2 = document.createEvent('HTMLEvents')
          event2.initEvent('resize', false, true)
          window.dispatchEvent(event2)
        })
      }
    })
  }
  render() {
    let IsMenus = this.state.IsMenus
    //自定义的空状态
    const customizeRenderEmpty = () => (
      <div style={{ textAlign: 'center', color:"rgba(0, 0, 0, 0.25)" }}>暂无数据</div>
    );
    if (this.state.loading) {
      return (
        <ConfigProvider locale={zhCN} renderEmpty={customizeRenderEmpty}>
          <HashRouter>
            {IsMenus === true ? (
              <Layout>
                {/* 头部如果有帮助文档需要显示，许需要传帮助文档对应的url
                           url://文档对应的地址
                           ex: <HeaderMenu url="******"></HeaderMenu> 
                           roleList:是否有角色切换功能（有则需要传值，否则不需要）
                           roleList={this.state.roleList}
                   */}
                <HeaderMenu></HeaderMenu>
                <div>
                  <Content
                    style={{
                      margin: '0 24px',
                      height: 'calc(100vh - 140px)',
                      background: '#fff',
                    }}
                  >
                    {
                      // setLeftMenu: 左侧菜单展开收缩的方法(必须传值)
                      //  isLeftMenuShow: 左侧菜单是否展开或者收缩(必须传值)
                      //level:左侧菜单需要从几级开始展示，最小3级。如有其他需求，可进行层级修改(必须传值)
                      //如果不需要左侧菜单可直接注释 左侧菜单组件，同时修改this.state.mainWidth值为100%。

                      <Leftmenu
                        setLeftMenu={this.setLeftMenu}
                        isLeftMenuShow={this.state.setLeftMenu}
                        level={3}
                      ></Leftmenu>
                      //this.state.mainWidth
                    }
                    <div
                      style={{
                        width: this.state.mainWidth,
                        height: '100%',
                        float: 'left',
                        overflowY: 'auto',
                        padding: '24px 0 0 0px',
                      }}
                    >
                      {routers.map((route, i) => (
                        <Route
                          key={i}
                          path={route.path}
                          render={(props) => (
                            <route.component {...props} routes={route.routes} />
                          )}
                        />
                      ))}
                    </div>
                    <div style={{ clear: 'both' }}></div>
                  </Content>
                </div>
                <Footer
                  style={{
                    height: '30px',
                    width: '100%',
                    lineHeight: '30px',
                    padding: '0px',
                    background: '#fff',
                    textAlign: 'center',
                    position: 'fixed',
                    bottom: '0',
                  }}
                >
                  <div>
                    © 2001-{new Date().getFullYear()} 版权所有
                    软通动力信息技术（集团）有限公司
                  </div>
                </Footer>
              </Layout>
            ) : null}
          </HashRouter>
        </ConfigProvider>
      )
    } else {
      return <div className="Myloading">Loading...</div>
    }
  }
}
export default SecondPages
